<?php

namespace iBrand\Shop\Backend\Service;

use iBrand\Component\Purchase\Repositories\PurchaseItemRepository;
use iBrand\Component\Goods\Models\Style;
use iBrand\Component\Goods\Models\Season;
use iBrand\Component\Purchase\Repositories\PurchaseRepository;
use DB;

class PurchaseService
{
	protected $purchaseItemRepository;
	protected $purchaseRepository;

	public function __construct(PurchaseItemRepository $purchaseItemRepository,
	                            PurchaseRepository $purchaseRepository)
	{
		$this->purchaseItemRepository = $purchaseItemRepository;
		$this->purchaseRepository     = $purchaseRepository;
	}

	public function getPurchaseDetailList($where, $time, $goods_ids, $product_ids, $limit = 20, $type = 'list')
	{
		$list = $this->purchaseItemRepository->scopeQuery(function ($query) use ($where, $time, $goods_ids, $product_ids) {
			if (!empty($where)) {
				foreach ($where as $key => $value) {
					if ($key == 'type' || $key == 'shop_id' || $key == 'code') {
						continue;
					}

					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($time)) {
				foreach ($time as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($goods_ids)) {
				$query = $query->whereIn('goods_id', $goods_ids);
			}

			if (!empty($product_ids)) {
				$query = $query->whereIn('item_id', $product_ids);
			}

			if (isset($where['type']) && $where['type']) {
				$type  = $where['type'];
				$query = $query->whereHas('purchase', function ($query) use ($type) {
					$query->where('type', $type);
				});
			}

			if (isset($where['shop_id']) && $where['shop_id']) {
				$shop_id = $where['shop_id'];
				$query   = $query->whereHas('purchase', function ($query) use ($shop_id) {
					$query->where('shop_id', $shop_id);
				});
			}

			if (isset($where['code']) && $where['code']) {
				$code  = $where['code'];
				$query = $query->whereHas('purchase', function ($query) use ($code) {
					$query->where('code', $code[0], $code[1]);
				});
			}

			return $query->with('purchase')->orderBy('created_at', 'desc');
		});

		if ($limit) {
			$list = $list->paginate(20);
		} else {
			$list = $list->all();
		}

		if ($type == 'list') {
			foreach ($list as $item) {
				$item->goodsName       = $item->meta['goods_name'];
				$item->goodsSn         = $item->product->goods->goods_no;
				$item->barCode         = $item->product->goods->goods_barcode;
				$item->colorName       = $item->meta['color_id'];
				$item->sizeName        = $item->meta['size_id'];
				$item->blandName       = $item->product->goods->brand->id;
				$item->categoryName    = $item->product->goods->categories()->orderBy('id', 'DESC')->first()->id;
				$item->styleName       = Style::where('id', $item->product->goods->style_id)->value('name');
				$item->seasonName      = Season::where('id', $item->product->goods->season_id)->value('name');
				$item->year            = $item->product->goods->year;
				$item->truePrice       = $item->purchase_price;
				$item->trueAmount      = $item->total;
				$item->ordersSn        = $item->purchase->code;
				$item->businessType    = $item->purchase->type_text;
				$item->handlerName     = $item->purchase->clerk->name;
				$item->trueTotalAmount = $item->purchase->total;
				$item->trueTotalAmount = $item->purchase->total;
				$item->businessTime    = date('Y-m-d H:i:s', strtotime($item->created_at));
				$item->remark          = $item->purchase->remark;
			}
		}

		return $list;
	}

	public function getPurchaseDetailExportData($list)
	{
		$data = [];
		if ($list && $list->count() > 0) {
			$i = 0;
			foreach ($list as $item) {
				$data[$i][] = $item->meta['goods_name'];
				$data[$i][] = $item->product->goods->goods_no;
				$data[$i][] = $item->product->goods->goods_barcode;
				$data[$i][] = $item->meta['color'];
				$data[$i][] = $item->meta['size'];
				$data[$i][] = $item->product->goods->brand->name;
				$data[$i][] = $item->product->goods->categories()->orderBy('id', 'DESC')->first()->name;
				$data[$i][] = $item->styleName;
				$data[$i][] = $item->seasonName;
				$data[$i][] = $item->product->goods->year;
				$data[$i][] = $item->quantity;
				$data[$i][] = $item->price;
				$data[$i][] = $item->discount . '%';
				$data[$i][] = $item->purchase_price;
				$data[$i][] = $item->total;
				$data[$i][] = $item->purchase->code;
				$data[$i][] = $item->purchase->type_text;
				$data[$i][] = $item->purchase->clerk->name;
				$data[$i][] = $item->purchase->total;
				$data[$i][] = date('Y-m-d H:i:s', strtotime($item->created_at));
				$data[$i][] = $item->purchase->remark;
				$i++;
			}
		}

		return $data;
	}

	public function getPurchaseDetailExportTitle()
	{
		return ['商品名称', '货号', '条码', '颜色', '尺码', '品牌', '分类', '款式', '季节', '年份', '单品数量', '单价', '折扣', '折后价', '总金额', '单号', '业务类别', '采购员', '单据总金额', '单据日期', '备注'];
	}

	public function getPurchaseGroupByHandlerList($where, $time, $limit = 20, $type = 'list')
	{
		$list = $this->purchaseRepository->scopeQuery(function ($query) use ($where, $time) {
			if (!empty($where)) {
				foreach ($where as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($time)) {
				foreach ($time as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			return $query->groupBy('clerk_id')->orderBy('clerk_id', 'desc');
		});

		if ($limit) {
			$list = $list->paginate(20, ['clerk_id', DB::raw('count(*) as total_order'), DB::raw('sum(quantity) as quantity'), DB::raw('sum(total) as trueAmount')]);
		} else {
			$list = $list->all(['clerk_id', DB::raw('count(*) as total_order'), DB::raw('sum(quantity) as quantity'), DB::raw('sum(total) as trueAmount')]);
		}

		if ($type == 'list') {
			foreach ($list as $item) {
				$item->handlerName = $item->clerk->name;
			}
		}

		return $list;
	}

	public function getPurchaseGroupByHandlerExportData($list)
	{
		$data = [];
		if ($list && $list->count() > 0) {
			$i = 0;
			foreach ($list as $item) {
				$data[$i][] = $item->quantity;
				$data[$i][] = $item->trueAmount;
				$data[$i][] = $item->clerk->name;
				$i++;
			}
		}

		return $data;
	}

	public function getPurchaseGroupByHandlerExportTitle()
	{
		return ['单品数量', '总金额', '采购员'];
	}

	public function getPurchaseGroupBySkuList($where, $time, $item_ids, $limit = 20, $type = 'list')
	{
		$list = $this->purchaseItemRepository->scopeQuery(function ($query) use ($where, $time, $item_ids) {
			if (!empty($where)) {
				foreach ($where as $key => $value) {
					if ($key == 'type' || $key == 'shop_id') {
						continue;
					}

					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($time)) {
				foreach ($time as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($item_ids)) {
				$query = $query->whereIn('item_id', $item_ids);
			}

			if (isset($where['type']) && $where['type']) {
				$type  = $where['type'];
				$query = $query->whereHas('purchase', function ($query) use ($type) {
					$query->where('type', $type);
				});
			}

			if (isset($where['shop_id']) && $where['shop_id']) {
				$shop_id = $where['shop_id'];
				$query   = $query->whereHas('purchase', function ($query) use ($shop_id) {
					$query->where('shop_id', $shop_id);
				});
			}

			return $query->groupBy('item_id')->groupBy('purchase_id')->orderBy('item_id', 'desc');
		});

		if ($limit) {
			$list = $list->paginate(20, ['*', DB::raw('sum(quantity) as quantity'), DB::raw('sum(total) as trueAmount')]);
		} else {
			$list = $list->all(['*', DB::raw('sum(quantity) as quantity'), DB::raw('sum(total) as trueAmount')]);
		}

		if ($type == 'list') {
			foreach ($list as $item) {
				$item->goodsName    = $item->meta['goods_name'];
				$item->goodsSn      = $item->product->goods->goods_no;
				$item->barCode      = $item->product->goods->goods_barcode;
				$item->colorName    = $item->meta['color_id'];
				$item->sizeName     = $item->meta['size_id'];
				$item->blandName    = $item->product->goods->brand->id;
				$item->categoryName = $item->product->goods->categories()->orderBy('id', 'DESC')->first()->id;
				$item->styleName    = Style::where('id', $item->product->goods->style_id)->value('name');
				$item->seasonName   = Season::where('id', $item->product->goods->season_id)->value('name');
				$item->year         = $item->product->goods->year;
				$item->truePrice    = $item->purchase_price;
			}
		}

		return $list;
	}

	public function getPurchaseGroupBySkuExportData($list)
	{
		$data = [];
		if ($list && $list->count() > 0) {
			$i = 0;
			foreach ($list as $item) {
				$data[$i][] = $item->meta['goods_name'];
				$data[$i][] = $item->product->goods->goods_no;
				$data[$i][] = $item->product->goods->goods_barcode;
				$data[$i][] = $item->meta['color'];
				$data[$i][] = $item->meta['size'];
				$data[$i][] = $item->product->goods->brand->name;
				$data[$i][] = $item->product->goods->categories()->orderBy('id', 'DESC')->first()->name;
				$data[$i][] = $item->styleName;
				$data[$i][] = $item->seasonName;
				$data[$i][] = $item->product->goods->year;
				$data[$i][] = $item->quantity;
				$data[$i][] = $item->price;
				$data[$i][] = $item->discount . '%';
				$data[$i][] = $item->purchase_price;
				$data[$i][] = $item->total;
				$i++;
			}
		}

		return $data;
	}

	public function getPurchaseGroupBySkuExportTitle()
	{
		return ['商品名称', '货号', '条码', '颜色', '尺码', '品牌', '分类', '款式', '季节', '年份', '单品数量', '单价', '折扣', '折后价', '总金额'];
	}

	public function getPurchaseGroupByGoodList($where, $time, $goods_ids, $limit = 20, $type = 'list')
	{
		$list = $this->purchaseItemRepository->scopeQuery(function ($query) use ($where, $time, $goods_ids) {
			if (!empty($where)) {
				foreach ($where as $key => $value) {
					if ($key == 'type' || $key == 'shop_id') {
						continue;
					}

					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($time)) {
				foreach ($time as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($goods_ids)) {
				$query = $query->whereIn('goods_id', $goods_ids);
			}

			if (isset($where['type']) && $where['type']) {
				$type  = $where['type'];
				$query = $query->whereHas('purchase', function ($query) use ($type) {
					$query->where('type', $type);
				});
			}

			if (isset($where['shop_id']) && $where['shop_id']) {
				$shop_id = $where['shop_id'];
				$query   = $query->whereHas('purchase', function ($query) use ($shop_id) {
					$query->where('shop_id', $shop_id);
				});
			}

			return $query->groupBy('goods_id')->orderBy('goods_id', 'desc');
		});

		if ($limit) {
			$list = $list->paginate(20, ['*', DB::raw('sum(quantity) as quantity'), DB::raw('sum(total) as trueAmount')]);
		} else {
			$list = $list->all(['*', DB::raw('sum(quantity) as quantity'), DB::raw('sum(total) as trueAmount')]);
		}

		if ($type == 'list') {
			foreach ($list as $item) {
				$item->goodsName    = $item->meta['goods_name'];
				$item->goodsSn      = $item->product->goods->goods_no;
				$item->barCode      = $item->product->goods->goods_barcode;
				$item->blandName    = $item->product->goods->brand->id;
				$item->categoryName = $item->product->goods->categories()->orderBy('id', 'DESC')->first()->id;
				$item->styleName    = Style::where('id', $item->product->goods->style_id)->value('name');
				$item->seasonName   = Season::where('id', $item->product->goods->season_id)->value('name');
				$item->year         = $item->product->goods->year;
				$item->truePrice    = $item->purchase_price;
			}
		}

		return $list;
	}

	public function getPurchaseGroupByGoodExportData($list)
	{
		$data = [];
		if ($list && $list->count() > 0) {
			$i = 0;
			foreach ($list as $item) {
				$data[$i][] = $item->meta['goods_name'];
				$data[$i][] = $item->product->goods->goods_no;
				$data[$i][] = $item->product->goods->goods_barcode;
				$data[$i][] = $item->product->goods->brand->name;
				$data[$i][] = $item->product->goods->categories()->orderBy('id', 'DESC')->first()->name;
				$data[$i][] = $item->styleName;
				$data[$i][] = $item->seasonName;
				$data[$i][] = $item->product->goods->year;
				$data[$i][] = $item->quantity;
				$data[$i][] = $item->price;
				$data[$i][] = $item->discount;
				$data[$i][] = $item->purchase_price;
				$data[$i][] = $item->trueAmount;
				$i++;
			}
		}

		return $data;
	}

	public function getPurchaseGroupByGoodExportTitle()
	{
		return ['商品名称', '货号', '条码', '品牌', '分类', '款式', '季节', '年份', '单品数量', '单价', '折扣', '折后价', '总金额'];
	}

	public function getPurchaseGroupByOrderList($where, $time, $limit = 20, $type = 'list')
	{
		$list = $this->purchaseRepository->scopeQuery(function ($query) use ($where, $time) {
			if (!empty($where)) {
				foreach ($where as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($time)) {
				foreach ($time as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			return $query->orderBy('created_at', 'desc');
		});

		if ($limit) {
			$list = $list->paginate($limit);
		} else {
			$list = $list->all();
		}

		if ($type == 'list') {
			foreach ($list as $item) {
				$item->handlerName     = $item->clerk->name;
				$item->ordersSn        = $item->code;
				$item->businessType    = $item->type_text;
				$item->trueTotalAmount = $item->total;
				$item->alreadyPaid     = $item->total;
				$item->businessTime    = date('Y-m-d H:i:s', strtotime($item->created_at));
			}
		}

		return $list;
	}

	public function getPurchaseGroupByOrderExportData($list)
	{
		$data = [];
		if ($list && $list->count() > 0) {
			$i = 0;
			foreach ($list as $item) {
				$data[$i][] = $item->quantity;
				$data[$i][] = $item->code;
				$data[$i][] = $item->type_text;
				$data[$i][] = $item->clerk->name;
				$data[$i][] = $item->total;
				$data[$i][] = date('Y-m-d H:i:s', strtotime($item->created_at));
				$data[$i][] = $item->remark;
				$i++;
			}
		}

		return $data;
	}

	public function getPurchaseGroupByOrderExportTitle()
	{
		return ['单品数量', '采购单号', '业务类型', '采购员', '单据总金额', '单据日期', '单据备注'];
	}
}